/*
 * @(#)JvmMonitorTask.java   1.0  2022年3月9日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.monitor.core.task;

import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.swift.core.cloud.NoDstb;
import com.swift.monitor.core.config.MonitorConfig;
import com.swift.monitor.core.notice.JvmMonitorNotice;
import com.swift.monitor.core.point.JvmPoint;
import com.swift.monitor.core.proxy.JvmManagement;
import com.swift.util.bean.BeanUtil;
import com.swift.util.type.IpUtil;

/**
 * 添加说明 
 * @author zhengjiajin
 * @version 1.0 2022年3月9日
 */
@Component
public class JvmMonitorTask {
    
    private JvmPoint sys_point = new JvmPoint();
    
    @Value("${sysId:}")
    private String sysId;
    
    @Autowired
    private JvmMonitorNotice jvmMonitorNotice;
    
    @PostConstruct
    public void start() {
        sys_point.setSysId(sysId);
        sys_point.setIp(IpUtil.getHostAddress());
        sys_point.setHostName(IpUtil.getHostName());
        sys_point.setProcessId(JvmManagement.getProcessId());
        long time = JvmManagement.getStartTime();
        if(time>0) {
            sys_point.setStartTime(new Date(time));
        }else {
            sys_point.setStartTime(new Date());
        }
        sys_point.setTotalPhysicalMemory(JvmManagement.getTotalPhysicalMemorySize());
        sys_point.setTotalSwapMemory(JvmManagement.getTotalSwapSpaceSize());
        sys_point.setTotalMemory(sys_point.getTotalPhysicalMemory()+sys_point.getTotalSwapMemory());
        sys_point.setMaxMemory(JvmManagement.getMaxHeapMemorySize());
    }
    
    @NoDstb
    @Scheduled(cron="0 * * * * ?")
    public void runMonitor() {
        if(!MonitorConfig.startMonitor) return;
        JvmPoint point = new JvmPoint();
        BeanUtil.copyProperties(point, sys_point);
        point.setPointTime(new Date());
        point.setSysCpuLate(JvmManagement.getSystemLoadAverage());
        point.setJvmCpuLate(JvmManagement.getProcessLoadAverage());
        point.setFreePhysicalMemory(JvmManagement.getFreePhysicalMemorySize());;
        point.setUseMemory(JvmManagement.getUsedHeapMemorySize());
        if(point.getMaxMemory()>0) {
            point.setMemoryLate((double)point.getUseMemory()/(double)point.getMaxMemory()); 
        }
        point.setThreadCount(JvmManagement.getPeakThreadCount());
        point.setCreateThreadCount(JvmManagement.getTotalStartedThreadCount());
        point.setRunThreadCount(JvmManagement.getRunThreadCount());
        point.setLockThreadCount(JvmManagement.findDeadlockedThreadCount());
        jvmMonitorNotice.notice(point);
    }
    
}
